package com.hr.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author DSL
 * @create 2024-10-28 16:44
 */
@Configuration// 配置类
public class MapperJavaConfig {
    /*
    * DataSource dataSource: 从spring容器中根据类型找到DataSource对象
    * */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
//        实例化
        SqlSessionFactoryBean sqlSessionFactoryBean=
                new SqlSessionFactoryBean();
//        设置连接池
        sqlSessionFactoryBean.setDataSource(dataSource);
//      settings 进行替换
        org.apache.ibatis.session.Configuration configuration=
                new org.apache.ibatis.session.Configuration();
//        开启驼峰映射
        configuration.setMapUnderscoreToCamelCase(true);
//        开启日志相关
        configuration.setLogImpl(Slf4jImpl.class);
//        开启自动映射
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
//        将数据放入到session
        sqlSessionFactoryBean.setConfiguration(configuration);
//        设置别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.hr.pojo");
//        分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
//        创建工具插件类
        Properties properties = new Properties();
//        将sql和helperDialect放入到工具类中
        properties.setProperty("helperDialect", "mysql");
//       将设置好的插件放到工厂类中
        sqlSessionFactoryBean.addPlugins(pageInterceptor);
//        最后返回工厂类
        return sqlSessionFactoryBean;
    }
//    创建扫描包的类 然后加入到Ioc 容器中
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer (){
        MapperScannerConfigurer mapperScannerConfigurer=
                new MapperScannerConfigurer();
//        设置扫描包
        mapperScannerConfigurer.setBasePackage("com.hr.mapper");
//        返回扫描类
        return mapperScannerConfigurer;
    }
}
